<!-- 合同管理-合同列表-新建合同 -->
<template>
  <pageHeader :title="title" :breadCrumb="breadCrumb" :show-back="true">
    <template #buts>
      <a-button @click="cancel"> 取消 </a-button>
      <a-button @click="addContract" type="primary"> 保存 </a-button>
    </template>
  </pageHeader>
  <div class="contract-index">
    <a-form
      ref="form"
      :model="contract.data"
      autoLabelWidth
      :layout="(layout as Tlayout)"
    >
      <a-row :gutter="16">
        <a-col
          v-for="element in contractForm?.data?.design?.form"
          :key="element.id"
          :span="element.span"
        >
          <FormItem
            :name="element.name"
            :componentType="element.componentType"
            v-model:props="element.props"
            :required="element.required"
            v-model:values="element.values"
          />
        </a-col>
      </a-row>
    </a-form>
  </div>
</template>

<script lang="ts" setup>
  import { ref, reactive, onMounted } from 'vue';
  import dayjs from 'dayjs';
  import {
    GetContractTemplateStatusOn,
    PostContract,
    postContractRecords,
    postSupplierContractRecords,
  } from '@/api/contract-management/contract-list/index';
  // import { GetContractTypeSetting } from '@/api/contract-management/base-setting/type-contract/index';
  import { useRouter, useRoute } from 'vue-router';
  import { number } from 'echarts';

  const router = useRouter();
  const route = useRoute();
  const title = '新建合同';
  const breadCrumb = ['合同管理', '合同列表', '新建合同'];

  const layout = ref('horizontal');
  type Tlayout = 'inline' | 'horizontal' | 'vertical' | undefined;
  const contract = reactive<any>({
    data: {
      number: '',
      name: '',
      extend: '',
      orderTime: undefined,
      supplierId: undefined,
      endTime: undefined,
      ourSignUser: undefined,
      clientCompanyId: undefined,
      templateId: undefined,
      totalPrice: '',
      state: undefined,
      receivingAccount: '',
      clientInvoiceID: '',
      invoiceId: '',
      ctotalPrice: '',
      createBy: JSON.parse(sessionStorage.getItem('loginInfo')).id, // 创建者id
      ctempTypeid: undefined,
    },
  });

  interface ContractFormType {
    data: {
      design: {
        form: any[];
      };
    };
  }
  const contractForm = reactive<ContractFormType>({
    data: { design: { form: [] } },
  });

  const id = Number(route.query.id);
  const idParent = Number(route.query.idParent);

  const getByTemplateStatusOn = async () => {
    let res = await GetContractTemplateStatusOn({
      ctempTypeid: route.query.id,
      ctempTypeidParent: route.query.idParent,
    });
    contractForm.data = res;
    contractForm.data.design.form.sort((a, b) => a.sort - b.sort);
    contractForm.data.design.form.forEach((item) => {
      item.props = JSON.parse(item.props);
      item.values = item.values ? JSON.parse(item.values)[0] || [] : [];
    });
  };

  const keys = Object.keys(contract.data);
  const addContract = async () => {
    // 控件对应上字段
    contractForm.data.design.form.forEach((item) => {
      if (item.fieldName && keys.includes(item.fieldName)) {
        if (item.fieldName === 'ctotalPrice') {
          contract.data.totalPrice = item.values.totalPrice;
          contract.data.totalUnit = item.values.totalUnit;
        } else contract.data[item.fieldName] = item.values[0];
      }
    });
    contract.data.totalPrice = contract.data.ctotalPrice;
    contract.data.templateId = contractForm.data.id; // 赋值模板id
    contract.data.extend = JSON.stringify(contractForm.data.design.form);
    // TODO:时间改成控件时间
    contract.data.orderTime = new Date(contract.data.orderTime).toJSON();
    contract.data.state = 1;
    contract.data.totalPrice = Number(contract.data.totalPrice);
    contract.data.endTime = new Date(contract.data.endTime).toJSON();
    contract.data.ctempTypeid = Number(route.query.id);
    contract.data.ctempTypeidParent = Number(route.query.idParent);
    delete contract.data.ctotalPrice;
    const res = await PostContract(contract.data);
    if (typeof res === 'object' && idParent === 1) {
      await postContractRecords({
        contractId: res.id,
        customerId: res.clientCompanyId,
      });
    } else if (typeof res === 'object' && idParent === 2) {
      await postSupplierContractRecords({
        supplierId: res.supplierId,
        contractId: res.id,
      });
    }
    router.back();
  };

  onMounted(() => {
    // 如果是添加则获取状态开启的那个模板
    getByTemplateStatusOn();
    // 如果是编辑则获取对应的模板
  });

  // 取消按钮
  const cancel = () => router.back();
</script>

<style scoped lang="less">
  .contract-index {
    padding: 30px;

    .addClient {
      position: absolute;
      margin-left: 20px;
      margin-top: -15px;
    }
  }
</style>
